package tr.edu.metu.is550.isell.rest.jersey.provider.mapper;

import tr.edu.metu.is550.isell.domain.ErrorCodes;
import tr.edu.metu.is550.isell.domain.ValidationException;
import tr.edu.metu.is550.isell.rest.message.ErrorMessages;

import javax.validation.ConstraintViolation;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import java.util.Iterator;
import java.util.Set;

@Provider
public class ValidationExceptionMapper implements ExceptionMapper<ValidationException> {
    @Override
    public Response toResponse(ValidationException exception) {
        ErrorMessages errorMessages = buildErrorMessagesEntity(exception);
        return Response.status(Response.Status.BAD_REQUEST).entity(errorMessages).build();
    }

    private ErrorMessages buildErrorMessagesEntity(ValidationException exception) {
        Set<ConstraintViolation<Object>> violations = exception.getViolations();
        Iterator<ConstraintViolation<Object>> iterator = violations.iterator();
        ErrorMessages errorMessages = new ErrorMessages();
        while (iterator.hasNext()) {
            ConstraintViolation<?> next = iterator.next();
            errorMessages.add(ErrorCodes.INVALID_INPUT, "Input is not valid", next.getMessage());
        }
        return errorMessages;
    }
}
